<?php

class PaymentReceiptJournalController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	
	/**
	 * @var string the form input mode
	 */
	public $inputMode= '';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','create','update','view', 'formaddrow', 'formdeleterow'),
				'roles'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new PaymentReceiptJournal;
		$model->voucherPrefix = PaymentReceiptJournal::VOUCHER_PREFIX;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PaymentReceiptJournal']))
		{
			$model->attributes=$_POST['PaymentReceiptJournal'];
		
			// tabular form PaymentReceiptJournalItemForm
			$modelPaymentReceiptJournalItemForm = array();
			$isValidPaymentReceiptJournalItem = false;
			if(isset($_POST['PaymentReceiptJournalItemForm']))
			{
				$items = Yii::app()->request->getPost('PaymentReceiptJournalItemForm');
				$isValidPaymentReceiptJournalItem = true;
				foreach ($items as $i => $item) 
				{
					$modelPaymentReceiptJournalItemForm[$i] = new PaymentReceiptJournalItemForm();
					$modelPaymentReceiptJournalItemForm[$i]->setAttributes($item);
					if($isValidPaymentReceiptJournalItem && !$modelPaymentReceiptJournalItemForm[$i]->validate())
					{
						$isValidPaymentReceiptJournalItem = false;
					}
				}
			}
			
			if(count($modelPaymentReceiptJournalItemForm) == 0)
			{
				$errorCount = count($model->getErrors());
				$model->addError($errorCount, 'Payment Receipt Item misssing');
			}
			
			$modelPaymentReceiptJournalItem = PaymentReceiptJournalItem::castFormToActiveRecord($modelPaymentReceiptJournalItemForm);
			$isTotalAmountValide = $this->validateDebitCreditListAmount($modelPaymentReceiptJournalItem);
			if($isTotalAmountValide == false)
			{
				$errorCount = count($modelPaymentReceiptJournalItemForm[0]->getErrors());
				$modelPaymentReceiptJournalItemForm[0]->addError($errorCount, 'Total debit and credit amount should equal.');
			}
			
			// finally save 
			// echo $isValidPaymentReceiptJournalItem == true ? 'isValidPaymentReceiptJournalItem=true':'isValidPaymentReceiptJournalItem=false';
			if($isValidPaymentReceiptJournalItem && $isTotalAmountValide) 
			{
				$transaction = Yii::app()->db->beginTransaction();
				
				try
				{
					$model->voucherPostfix = $this->getNextVoucherPostfix();
					$createDate = $model->createDate;
					// save journal 
					if(!$model->save())
					{	
						Yii::log('failed to save PaymentReceiptJournal: '.var_export($model->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save journal');
					}
					
					// save journal items
					foreach($modelPaymentReceiptJournalItem as $item) 
					{
						// create gl transaction debit
						$glTransaction = new GlTransaction();
						$glTransaction->voucherPrefix = $model->voucherPrefix;
						$glTransaction->voucherPostfix = $model->voucherPostfix;
						$glTransaction->createDate = $createDate;
						$glTransaction->glId = $item->glId;
						$glTransaction->isDebit = $item->isDebit;
						$glTransaction->amount = $item->amount;
						$glTransaction->narration = $item->narration;
						
						if(!$glTransaction->save())
						{
							Yii::log('failed to save GL Transaction:'.var_export($glTransaction->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save Gl Transaction');
						}
						
						// save payment receipt journal item id
						$item->glTransactionId = $glTransaction->id;					
						$item->paymentReceiptJournalId = $model->id;
						if(!$item->save())
						{
							Yii::log('failed to save PaymentReceiptJournalItem: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save items');
						}
					}
					
					$transaction->commit();
					$this->redirect(array('view','id'=>$model->id));
				} 
				catch (Exception $ex) 
				{
					$transaction->rollback();
					// $errorCount = count($model->getErrors());
					// $model->addError($errorCount, $ex->getMessage());
				}
			}
		}
		
		$this->render('create',array(
			'model'=>$model,
			'modelPaymentReceiptJournalItem'=>$modelPaymentReceiptJournalItemForm,
		));
	}
	
	/**
	 * creates a new model row for tabular form.
	 * will show tabular form with new row.
	 */
	public function actionFormAddRow()
	{
		if(Yii::app()->request->isAjaxRequest) {
			$items = Yii::app()->request->getPost('PaymentReceiptJournal');
			
			$modelPaymentReceiptJournal = array();
			
			if (is_array($items)) { 
				//creating existing model instances + setting attributes
				foreach ($items as $i => $item) {
					$modelPaymentReceiptJournal[$i] = new PaymentReceiptJournal();
					$modelPaymentReceiptJournal[$i]->setAttributes($item);
				}
			}
            //creating an additional empty model instance
            $modelPaymentReceiptJournal[] = new PaymentReceiptJournal();
            
            echo $this->renderPartial('application.views.paymentReceiptJournal/_tabularform_additional', array("modelPaymentReceiptJournal" => $modelPaymentReceiptJournal));
            exit;

        } else {
            throw new CHttpException(404, 'Unable to resolve the request');
        }
	}
	
	/**
	 * delete model row for tabular form.
	 * will show tabular form with delete row.
	 */
	public function actionFormDeleteRow()
	{
		if(Yii::app()->request->isAjaxRequest) {
			$items = Yii::app()->request->getPost('PaymentReceiptJournal');
			$rowIndex = Yii::app()->request->getPost('rowIndex');
			unset($items[$rowIndex]);
			$modelPaymentReceiptJournal = array();
			
			if (is_array($items)) { 
				//creating existing model instances + setting attributes
				$i = 0;
				foreach ($items as $item) {
					$modelPaymentReceiptJournal[$i] = new PaymentReceiptJournal();
					$modelPaymentReceiptJournal[$i]->setAttributes($item);
					$i++;
				}
			}
            
            echo $this->renderPartial('application.views.paymentReceiptJournal/_tabularform_additional', array("modelPaymentReceiptJournal" => $modelPaymentReceiptJournal));
            exit;

        } else {
            throw new CHttpException(404, 'Unable to resolve the request');
        }
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$this->inputMode = 'edit';
		$model=$this->loadModel($id);
		$modelPaymentReceiptJournalItemForm = array();
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PaymentReceiptJournal']))
		{
			$model->attributes=$_POST['PaymentReceiptJournal'];
		
			// initialize and validate PaymentReceiptJournalItemForm
			$modelPaymentReceiptJournalItemIds = array();
			$isValidPaymentReceiptJournalItem = false;
			if(isset($_POST['PaymentReceiptJournalItemForm']))
			{
				$items = Yii::app()->request->getPost('PaymentReceiptJournalItemForm');
				$isValidPaymentReceiptJournalItem = true;
				// var_dump($items);
				foreach ($items as $i => $item) 
				{
					$modelPaymentReceiptJournalItemForm[$i] = new PaymentReceiptJournalItemForm();
					$modelPaymentReceiptJournalItemForm[$i]->setAttributes($item);
					
					if(!empty($modelPaymentReceiptJournalItemForm[$i]->id))
						$modelPaymentReceiptJournalItemIds[] = $modelPaymentReceiptJournalItemForm[$i]->id;
					
					if($isValidPaymentReceiptJournalItem && !$modelPaymentReceiptJournalItemForm[$i]->validate())
					{
						$isValidPaymentReceiptJournalItem = false;
					}
				}
				// var_dump($modelPaymentReceiptJournalItemForm);
			}
			
			// journal item should not be zero
			if(count($modelPaymentReceiptJournalItemForm) == 0)
			{
				$errorCount = count($model->getErrors());
				$model->addError($errorCount, 'Payment Receipt Item misssing');
			}
			
			// validate journal item debit/credit total amount
			$modelPaymentReceiptJournalItem = PaymentReceiptJournalItem::castFormToActiveRecord($modelPaymentReceiptJournalItemForm, TRUE);
			$isTotalAmountValide = $this->validateDebitCreditListAmount($modelPaymentReceiptJournalItem);
			if($isTotalAmountValide == FALSE)
			{
				$errorCount = count($modelPaymentReceiptJournalItemForm[0]->getErrors());
				$modelPaymentReceiptJournalItemForm[0]->addError($errorCount, 'Total debit and credit amount should equal.');
			}
			
			// finally save 
			// echo $isValidPaymentReceiptJournalItem == true ? 'isValidPaymentReceiptJournalItem=true':'isValidPaymentReceiptJournalItem=false';
			if($isValidPaymentReceiptJournalItem && $isTotalAmountValide) 
			{
				$transaction = Yii::app()->db->beginTransaction();
				
				try
				{
					$createDate = $model->createDate;
					// save journal 
					if($model->save() === FALSE)
					{
						Yii::log('failed to save PaymentReceiptJournal: '.var_export($model->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save journal');
					}
					
					// save journal items and create gl transaction
					// delete user deleted payment receipt journal items and gl transactions.
					$glTransactionIds = '';
					$paymentReceiptJournalItemsIds = '';
					if(count($modelPaymentReceiptJournalItemIds) == 0)
					{
						$row = Yii::app()->db->createCommand("SELECT GROUP_CONCAT( glTransactionId SEPARATOR  ',' ) as glTransactionIds, GROUP_CONCAT( id SEPARATOR  ',' ) as paymentReceiptJournalItemsIds FROM paymentreceiptjournalitem WHERE paymentReceiptJournalId =$model->id")->queryRow();
						$glTransactionIds = $row['glTransactionIds'];
						$paymentReceiptJournalItemsIds = $row['paymentReceiptJournalItemsIds'];

					}
					else
					{
						$row = Yii::app()->db->createCommand("SELECT GROUP_CONCAT( glTransactionId SEPARATOR  ',' ) as glTransactionIds, GROUP_CONCAT( id SEPARATOR  ',' ) as paymentReceiptJournalItemsIds FROM paymentreceiptjournalitem WHERE paymentReceiptJournalId=$model->id AND id NOT IN (".implode(',', $modelPaymentReceiptJournalItemIds).")")->queryRow();
						$glTransactionIds = $row['glTransactionIds'];
						$paymentReceiptJournalItemsIds = $row['paymentReceiptJournalItemsIds'];
					}
					// var_dump($row); exit;
					
					if(!empty($paymentReceiptJournalItemsIds))
					{
						Yii::app()->db->createCommand("delete from paymentreceiptjournalitem where id IN ($paymentReceiptJournalItemsIds)" )->query();
						Yii::app()->db->createCommand("delete from gltransaction where id IN ($glTransactionIds)")->query();
					}
					
					
					foreach($modelPaymentReceiptJournalItem as $item) 
					{
						if(empty($item->glTransactionId))
						{
							// create gl transaction debit
							$glTransaction = new GlTransaction();
							$glTransaction->voucherPrefix = $model->voucherPrefix;
							$glTransaction->voucherPostfix = $model->voucherPostfix;
							$glTransaction->createDate = $createDate;
							$glTransaction->glId = $item->glId;
							$glTransaction->isDebit = $item->isDebit;
							$glTransaction->amount = $item->amount;
							$glTransaction->narration = $item->narration;
							
						}
						else
						{
							$glTransaction = GlTransaction::model()->findByPk($item->glTransactionId);
							$glTransaction->createDate = $createDate;
							$glTransaction->glId = $item->glId;
							$glTransaction->isDebit = $item->isDebit;
							$glTransaction->amount = $item->amount;
							$glTransaction->narration = $item->narration;
						}
						
						if(!$glTransaction->save())
						{
							Yii::log('failed to save GL Transaction:'.var_export($glTransaction->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save Gl Transaction');
						}
						
						// save payment receipt journal item id
						$item->glTransactionId = $glTransaction->id;
						
						$item->paymentReceiptJournalId = $model->id;
						if(!$item->save())
						{
							Yii::log('failed to save PaymentReceiptJournalItem: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save items');
						}
						
					}
					
					$transaction->commit();
					$this->redirect(array('view','id'=>$model->id));
				} 
				catch (Exception $ex) 
				{
					$transaction->rollback();
					// $errorCount = count($model->getErrors());
					// $model->addError($errorCount, $ex->getMessage());
				}
			}
		}
		else
		{
			// load journal items 
			$modelPaymentReceiptJournalItem = PaymentReceiptJournalItem::model()->findAll(array(
				'condition'=>'paymentReceiptJournalId=:paymentReceiptJournalId',
				'params'=>array(':paymentReceiptJournalId'=>$model->id),
			));
			
			// cast to form
			$modelPaymentReceiptJournalItemForm = PaymentReceiptJournalItem::castActiveRecordToForm($modelPaymentReceiptJournalItem);
		}
		$this->render('update',array(
			'model'=>$model,
			'modelPaymentReceiptJournalItem'=>$modelPaymentReceiptJournalItemForm,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('PaymentReceiptJournal');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new PaymentReceiptJournal('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PaymentReceiptJournal']))
			$model->attributes=$_GET['PaymentReceiptJournal'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=PaymentReceiptJournal::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='payment-receipt-journal-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * generate next voucher number.
	 */
	protected function getNextVoucherPostfix()
	{
		$criteria=new CDbCriteria;
		$criteria->select='max(voucherPostfix) as voucherPostfix';
		$criteria->condition = 'voucherPrefix=:voucherPrefix';
		$criteria->params = array(':voucherPrefix'=>PaymentReceiptJournal::VOUCHER_PREFIX);
		$maxPostfixRow = PaymentReceiptJournal::model()->find($criteria);
		return $maxPostfixRow['voucherPostfix'] + 1;
	}

	/**
	 * validate debit and credit amount both are equal.
	 */
	public static function validateDebitCreditListAmount($items)
	{
		$amountDebit = 0;
		$amountCredit = 0; 
		
		foreach($items as $i => $item)
		{
			if($item->isDebit)
				$amountDebit += $item->amount;
			else
				$amountCredit += $item->amount;
				
		}
		// echo count($items), '=', $amountDebit, '==', $amountCredit; exit;
		return ($amountDebit == $amountCredit ? true : false);
	}
	
}
